package com.sgb.kjwl.view.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.RelativeLayout;

import androidx.fragment.app.Fragment;
import androidx.navigation.NavArgument;
import androidx.navigation.NavController;
import androidx.navigation.NavGraph;
import androidx.navigation.Navigation;
import androidx.navigation.fragment.NavHostFragment;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.gyf.barlibrary.ImmersionBar;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.swgk.core.event.EventConstant;
import com.swgk.core.event.MenuEvent;
import com.sgb.kjwl.view.event.WebEvent;
import com.swgk.core.base.aroute.AppRouteConstant;
import com.ycbjie.webviewlib.view.X5WebView;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * Created by harisucici on 2020/5/12
 * Class description:
 */
@Route(path = AppRouteConstant.WEB_ROUTE_URL)
public class WebViewX5HostActivity extends AppActivity {
    public final static String URL = "url";
    public final static String ID = "id";
    public final static String TAG = "WebViewX5HostActivity";
    public final static String TYPE = "TYPE";
    public final static String STATE = "STATE";
    public final static String TEXT = "TEXT";
    @Autowired(name = "webUrl")
    public  String webUrl;
    @Autowired(name = "id")
    public   String ids;
    @Autowired(name = "types")
    public   String types;
    @Autowired(name = "isARouter")
    public   boolean isARouter;
    public ImmersionBar immersionBar;
    NavHostFragment navHostFragment;
    WebViewX5Fragment webViewX5Fragment;
    private RelativeLayout rlLoadingView;

    public static void start(Context context, String url) {
        Intent intent = new Intent();
        intent.setClass(context, WebViewX5HostActivity.class);
        intent.putExtra(URL, url);
        context.startActivity(intent);
    }

    public static void startForEmploymentRelease(Context context, String url,String name) {
        Intent intent = new Intent();
        intent.setClass(context, WebViewX5HostActivity.class);
        intent.putExtra(URL, url);
        intent.putExtra("name", name);
        context.startActivity(intent);
    }

    public static void start(Context context, String url, int requestCode) {
        Intent intent = new Intent();
        intent.setClass(context, WebViewX5HostActivity.class);
        intent.putExtra(URL, url);
        ((Activity) context).startActivityForResult(intent, requestCode);
    }

    public static void start(Context context, String url,String text, int requestCode) {
        Intent intent = new Intent();
        intent.setClass(context, WebViewX5HostActivity.class);
        intent.putExtra(URL, url);
        intent.putExtra(TEXT, text);
        ((Activity) context).startActivityForResult(intent, requestCode);
    }

    public static void start(Context context,String url,String id) {
        Intent intent = new Intent();
        intent.setClass(context, WebViewX5HostActivity.class);
        intent.putExtra(URL, url);
        intent.putExtra(ID, id);
        context.startActivity(intent);
    }

    public static void start(Context context,String url,String id,String type,String state) {
        Intent intent = new Intent();
        intent.setClass(context, WebViewX5HostActivity.class);
        intent.putExtra(URL, url);
        intent.putExtra(ID, id);
        intent.putExtra(TYPE, type);
        intent.putExtra(STATE, state);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view_x5_host);
        rlLoadingView = findViewById(R.id.rl_loadingView);
        rlLoadingView.setVisibility(View.VISIBLE);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        immersionBar = ImmersionBar.with(this)
                .statusBarDarkFont(false)
                .fitsSystemWindows(false)
                .keyboardEnable(false)
                .keyboardMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN | WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        immersionBar.init();
        webViewX5Fragment = (WebViewX5Fragment) getPrimaryFragment(WebViewX5Fragment.class);
  /*      if (!TextUtils.isEmpty(getIntent().getStringExtra(URL))) {
            webViewX5Fragment.loadUrl(getIntent().getStringExtra(URL));
        }
        if (!TextUtils.isEmpty(getIntent().getStringExtra(ID))) {
            webViewX5Fragment.setId(getIntent().getStringExtra(ID));
        }
        if (!TextUtils.isEmpty(getIntent().getStringExtra(TYPE))) {
            webViewX5Fragment.setType(getIntent().getStringExtra(TYPE));
        }*/
        initdataView();
    }

    public void closeLoadingView() {
        rlLoadingView.setVisibility(View.GONE);
    }

    private void initdataView() {
        if (isARouter){
            if (!TextUtils.isEmpty(webUrl)) {
                webViewX5Fragment.loadUrl(webUrl);
            }
            if (!TextUtils.isEmpty(ids)) {
                webViewX5Fragment.setId(ids);
            }
            if (!TextUtils.isEmpty(types)) {
                webViewX5Fragment.setType(getIntent().getStringExtra(types));
            }
        }else {
            String url = getIntent().getStringExtra(URL);
            if (!TextUtils.isEmpty(url)) {
                webViewX5Fragment.loadUrl(url);
            }
            if (!TextUtils.isEmpty(getIntent().getStringExtra(ID))) {
                webViewX5Fragment.setId(getIntent().getStringExtra(ID));
            }
            if (!TextUtils.isEmpty(getIntent().getStringExtra(TYPE))) {
                webViewX5Fragment.setType(getIntent().getStringExtra(TYPE));
            }

            if (!TextUtils.isEmpty((getIntent().getStringExtra("name")))){
                webViewX5Fragment.setTitle((getIntent().getStringExtra("name")));
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (webViewX5Fragment.isEdt){
            webViewX5Fragment.isEdt = false;
            if (isARouter){
                if (!TextUtils.isEmpty(webUrl)) {
                    webViewX5Fragment.loadUrl(webUrl);
                }
            }else {
                if (!TextUtils.isEmpty(getIntent().getStringExtra(URL))) {
                    webViewX5Fragment.loadUrl(getIntent().getStringExtra(URL));
                }
            }
       /*     if (!TextUtils.isEmpty(getIntent().getStringExtra(URL))) {
                webViewX5Fragment.loadUrl(getIntent().getStringExtra(URL));
            }*/
        }
    }

    private Fragment getCFragment() {
        Log.d(TAG, "Primary=" + getSupportFragmentManager().getPrimaryNavigationFragment());
        Log.d(TAG, "Fragment by id =" + getSupportFragmentManager().findFragmentById(R.id.fragmentX5));
        Log.d(TAG, "FragmentList =" + getSupportFragmentManager().getFragments());
        Log.d(TAG, "Fragment=" + getSupportFragmentManager().getFragments().get(0));
        return getSupportFragmentManager().findFragmentById(R.id.fragmentX5);
    }

    public Fragment getPrimaryFragment(Class<?> clazz) {
        for (Fragment fragment : getCFragment().getChildFragmentManager().getFragments()) {
            if (clazz.isAssignableFrom(fragment.getClass())) {
                return fragment;
            }
        }
        return null;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        X5WebView mWebView = WebViewX5Fragment.getWebView();
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!TextUtils.isEmpty(mWebView.getUrl()) && mWebView.getUrl().contains("successDetail")){//函询
                setResult(RESULT_OK);
                finish();
            } else {
                if (mWebView.canGoBack()){
                    mWebView.goBack();
                    return true;
                } else {
                    finish();
                }
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        immersionBar.destroy();
        closeLoadingView();
        EventBus.getDefault().unregister(this);
    }

    private void setupNavigation() {
        NavController controller = Navigation.findNavController(this, R.id.fragmentX5);
        NavGraph graph = controller.getGraph();
        NavArgument argument = new NavArgument.Builder().setDefaultValue(getIntent().getStringExtra(URL)).build();
        graph.addArgument(URL, argument);

        webViewX5Fragment.loadUrl(getIntent().getStringExtra(URL));
    }

    /**
     * 上传图片之后的回调
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        Log.e("onActivityResult", "onActivityResult");
        webViewX5Fragment.ActivityResult(requestCode, resultCode, intent);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MenuEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_ORDER_FINISH || event.getMessageTag() == EventConstant.EVENT_MEMBER_APPROVAL_SUCCESS) {
            EventBus.getDefault().postSticky(WebEvent.make().setMessageTag(EventConstant.EVENT_MEMBER_APPROVAL_REFRESH));
            finish();
        }
        EventBus.getDefault().removeStickyEvent(event);
    }
}
